package com.taylor.netty.group;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @Desc : netty 群聊客户端
 * @Author ： taylor
 * @Date ：2021/7/5 21:42
 */
public class NettyChatClient {
    //属性
    private final String host;
    private final int port;

    public NettyChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyChatClient("127.0.0.1", 8888).run();
    }

    private void run() throws InterruptedException {

        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //加入相关handler
                        pipeline.addLast("decoder", new StringDecoder());
                        pipeline.addLast("encoder", new StringEncoder());
                        pipeline.addLast(new ChatClientHandler());
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
        Channel channel = channelFuture.channel();
        System.out.println("-------" + channel.localAddress() + "--------");
        //客户端需要输入信息，创建一个扫描器
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            //通过channel 发送到服务器端
            channel.writeAndFlush(msg + "\r\n");
        }

        eventLoopGroup.shutdownGracefully();
    }
}
